﻿using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Security.Principal;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Security;
using LeadVinaglue.Models;
using LeadVinaglue.Repository;
using LeadVinaglue.Models.ViewPages;
using LeadVinaglue.Utility;

namespace LeadVinaglue.Controllers
{
    public class AccountController : BaseController
    {
        EFRoleProvider provider = new EFRoleProvider();
        public IFormsAuthenticationService FormsService { get; set; }
        public IMembershipService MembershipService { get; set; }

        protected override void Initialize(RequestContext requestContext)
        {
            if (FormsService == null) { FormsService = new FormsAuthenticationService(); }
            if (MembershipService == null) { MembershipService = new AccountMembershipService(); }

            base.Initialize(requestContext);
        }

        // **************************************
        // URL: /Account/LogOn
        // **************************************

        [DeviceFilterAttribute(Order = 1)]
        public ActionResult LogOn()
        {
            return Redirect("/signin");
        }

        [HttpPost]
        public ActionResult LogOn(LogOnModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                if (MembershipService.ValidateUser(model.UserName, model.Password))
                {
                    FormsService.SignIn(model.UserName, model.RememberMe);

                    // Get role to switch mode login
                    // Current: Login is default for client
                    EFRoleProvider provider = new EFRoleProvider();
                    string[] roles = provider.GetRolesForUser(model.UserName);
                    bool isAdmin = false;
                    bool isClient = false;

                    if (roles.Length > 0)
                    {
                        foreach (string role in roles)
                        {
                            if (role.ToUpper() == "SUPERADMINISTRATOR")
                                isAdmin = true;
                            else if (role.ToUpper() == "CLIENTADMIN")
                                isClient = true;
                        }

                        if (isAdmin)
                        {
                            if (Url.IsLocalUrl(returnUrl))
                            {
                                return Redirect(returnUrl);
                            }
                            else
                            {
                                return RedirectToAction("Index", "Home");
                            }
                        }
                        else if (isClient)
                        {
                            if (Url.IsLocalUrl(returnUrl))
                            {
                                return Redirect(returnUrl);
                            }
                            else
                            {
                                return RedirectToAction("Index", "Home");
                            }
                        }
                    }
                }
                else
                {
                    ModelState.AddModelError("", "The user name or password provided is incorrect.");
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }

        // **************************************
        // URL: /Account/LogOff
        // **************************************

        [DeviceFilterAttribute(Order = 1)]
        public ActionResult LogOff()
        {
            FormsService.SignOut();

            return RedirectToAction("Index", "Home");
        }

        // **************************************
        // URL: /Account/Register
        // **************************************

        [DeviceFilterAttribute(Order = 1)]
        public ActionResult Register()
        {
            ViewBag.PasswordLength = MembershipService.MinPasswordLength;
            return View();
        }

        [HttpPost]
        public ActionResult Register(RegisterModel model)
        {
            if (ModelState.IsValid)
            {
                // Attempt to register the user
                MembershipCreateStatus createStatus = MembershipService.CreateUser(model.Email, model.Password, model.Email);

                if (createStatus == MembershipCreateStatus.Success)
                {
                    FormsService.SignIn(model.Email, false /* createPersistentCookie */);
                    return RedirectToAction("Index", "Home");
                }
            }

            // If we got this far, something failed, redisplay form
            ViewBag.PasswordLength = MembershipService.MinPasswordLength;
            return View(model);
        }

        // **************************************
        // URL: /Account/ChangePassword
        // **************************************

        [DeviceFilterAttribute(Order = 1)]
        [Authorize]
        public ActionResult ChangePassword()
        {
            ViewBag.PasswordLength = MembershipService.MinPasswordLength;
            return View();
        }

        [Authorize]
        [HttpPost]
        public ActionResult ChangePassword(ChangePasswordModel model)
        {
            if (ModelState.IsValid)
            {
                if (MembershipService.ChangePassword(User.Identity.Name, model.OldPassword, model.NewPassword))
                {
                    return RedirectToAction("ChangePasswordSuccess");
                }
                else
                {
                    ModelState.AddModelError("", "The current password is incorrect or the new password is invalid.");
                }
            }

            // If we got this far, something failed, redisplay form
            ViewBag.PasswordLength = MembershipService.MinPasswordLength;
            return View(model);
        }

        // **************************************
        // URL: /Account/ChangePasswordSuccess
        // **************************************

        [DeviceFilterAttribute(Order = 1)]
        public ActionResult ChangePasswordSuccess()
        {
            return View();
        }


        // Active/Deactive account
        [DeviceFilterAttribute(Order=1)]
        public ActionResult Activate(string guid, string email)
        {
            RegisterManagementRepository repository = new RegisterManagementRepository();
            RegisterManagementModel model = new RegisterManagementModel();

            // Setup common
            SetupCommon(model);

            repository.GetModel(ref model, LeadConstant.REGISTER);

            // Active User
            UserRepository uRepository = new UserRepository();
            var user = uRepository.GetSingle(email);
            if (user != null)
            {
                // Check role
                bool isExistRole = provider.IsUserInRole(email, "ClientAdmin");
                if (user.GUID.Equals(guid))
                {
                    user.IsApproved = true;
                    user.IsLockedOut = false;
                    user.Active = true;
                    uRepository.Save(user);
                    model.ErrorMessages = "Bạn vừa kích hoạt tài khoản thành công. Bạn có thể đăng nhập hệ thống vinaglue.com.";
                }
                else
                    model.ErrorMessages = "Tài khoản đã được kích hoạt.";
                model.Fullname = user.Fullname;
            }
            else
                model.ErrorMessages = "Tài khoản không tồn tại hoặc đã được kích hoạt.";

            return View(model);
        }

        // Active/Deactive account
        public ActionResult DeActivate(string guid, string email)
        {
            RegisterManagementRepository repository = new RegisterManagementRepository();
            RegisterManagementModel model = new RegisterManagementModel();

            // Setup common
            SetupCommon(model);

            repository.GetModel(ref model, LeadConstant.REGISTER);

            // Active User
            UserRepository uRepository = new UserRepository();
            var user = uRepository.GetSingle(email);
            if (user != null)
            {
                // Check role
                bool isExistRole = provider.IsUserInRole(email, "ClientAdmin");
                if (isExistRole && user.GUID.Equals(guid))
                {
                    user.IsApproved = true;
                    user.IsLockedOut = false;
                    user.Active = true;
                    uRepository.Save(user);

                    return RedirectToAction("Index", "Home");
                }
                else
                    model.ErrorMessages = "Tài khoản không tồn tại hoặc đã được kích hoạt.";
                model.Fullname = user.Fullname;
            }
            else
                model.ErrorMessages = "Tài khoản không tồn tại hoặc đã được kích hoạt.";


            return View(model);
        }
    }
}
